package com.choichumgming.rentcat.service.Impl;

import com.choichumgming.rentcat.mapper.PmsProductMapper;
import com.choichumgming.rentcat.model.PmsProduct;
import com.choichumgming.rentcat.model.PmsProductExample;
import com.choichumgming.rentcat.repository.EsProductRepository;
import com.choichumgming.rentcat.service.PmsEsProductService;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * 商品搜索管理Service实现类
 */
@Service
public class PmsEsProductServiceImpl implements PmsEsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PmsEsProductServiceImpl.class);

    @Autowired
    private EsProductRepository productRepository;
    @Autowired
    private PmsProductMapper pmsProductMapper;

    /**
     * @Description : 导入所有数据库中商品到ES
     *
     * @Return : int
     * @Author : choichumgming
     * @Date : 2/3/2020 14:35
    */
    @Override
    public int importAll() {
        PmsProductExample example = new PmsProductExample();
        List<PmsProduct> productList = pmsProductMapper.selectByExample(example);
        Iterable<PmsProduct> productIterable = productRepository.saveAll(productList);
        Iterator<PmsProduct> iterator = productIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    /**
     * @Description : 根据id删除商品
     *
     * @param id
     * @Return : void
     * @Author : choichumgming
     * @Date : 2/3/2020 14:35
    */
    @Override
    public void delete(Long id) {
        productRepository.deleteById(id);
    }

    /**
     * @Description : 根据id批量删除商品
     *
     * @param ids
     * @Return : void
     * @Author : choichumgming
     * @Date : 2/3/2020 14:35
     */
    @Override
    public void delete(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<PmsProduct> esProductList = new ArrayList<>();
            for (Long id : ids) {
                PmsProduct esProduct = new PmsProduct();
                esProduct.setProductId(id);
                esProductList.add(esProduct);
            }
            productRepository.deleteAll(esProductList);
        }
    }

    /**
     * @Description : 根据id创建商品
     *
     * @param id
     * @Return : com.choichumgming.rentcat.domain.EsProduct
     * @Author : choichumgming
     * @Date : 2/3/2020 14:35
    */
    @Override
    public PmsProduct create(Long id) {
        PmsProduct result = null;
        PmsProduct esProduct = pmsProductMapper.selectByPrimaryKey(id);
        result = productRepository.save(esProduct);
        return result;
    }


    /**
     * @Description : 简单搜索
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @Return : org.springframework.data.domain.Page<com.choichumgming.rentcat.domain.EsProduct>
     * @Author : choichumgming
     * @Date : 2/3/2020 14:35
    */
    @Override
    public Page<PmsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return productRepository.findByNameOrKeywords(keyword, keyword, pageable);
    }


    /**
     * @Description : 综合搜索、筛选、排序
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @param sort
     * @Return : org.springframework.data.domain.Page<com.choichumgming.rentcat.domain.EsProduct>
     * @Author : choichumgming
     * @Date : 2/3/2020 14:35
    */
    @Override
    public Page<PmsProduct> search(String keyword, Integer pageNum, Integer pageSize,Integer sort) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);

        //搜索
        if (StringUtils.isEmpty(keyword)) {
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
        } else {
            List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(10)));
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("description", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(5)));
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(2)));
            FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
            filterFunctionBuilders.toArray(builders);
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                    .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                    .setMinScore(2);
            nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
        }
        //排序
        if(sort==1){
            //按新品从新到旧
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("productId").order(SortOrder.DESC));
        }else if(sort==2){
            //按新品从旧到新
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("productId").order(SortOrder.ASC));
        }else if(sort==3){
            //按价格从低到高
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
        }else if(sort==4){
            //按价格从高到低
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
        }else{
            //按相关度
            nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        }
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        return productRepository.search(searchQuery);
    }

    /**
     * @Description : 根据商品id推荐商品
     *
     * @param id
     * @param pageNum
     * @param pageSize
     * @Return : org.springframework.data.domain.Page<com.choichumgming.rentcat.domain.EsProduct>
     * @Author : choichumgming
     * @Date : 2/3/2020 14:38
    */
    @Override
    public Page<PmsProduct> recommend(Long id, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
            PmsProduct esProduct = pmsProductMapper.selectByPrimaryKey(id);
            String keyword = esProduct.getName();
            Long productCategoryId = esProduct.getProductCategoryId();
            //根据商品描述、分类进行搜索
            List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(8)));
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("description", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(2)));
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productCategoryId", productCategoryId),
                    ScoreFunctionBuilders.weightFactorFunction(6)));
            FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
            filterFunctionBuilders.toArray(builders);
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                    .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                    .setMinScore(2);
            NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
            builder.withQuery(functionScoreQueryBuilder);
            builder.withPageable(pageable);
            NativeSearchQuery searchQuery = builder.build();
            LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
            return productRepository.search(searchQuery);
    }


}
